package fi.internetix.tidyclipboard;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import fi.internetix.ck.HTMLCleanup;

public class Servlet extends HttpServlet {

  private static final long serialVersionUID = -2360049656988503178L;

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();
    JSONObject response = new JSONObject();
    try {
      try {
        String htmlData = req.getParameter("htmlData");
        HTMLCleanup htmlCleanup = new HTMLCleanup();

        String cleanedData = htmlCleanup.cleanupHTML(htmlData);

        if (logger.getLevel().isGreaterOrEqual(Level.DEBUG))
          logger.debug(htmlData + " cleaned to " + cleanedData);

        response.put("htmlData", cleanedData);

      } catch (Exception e) {
        response.put("error", e.getMessage());
        logger.error(e);
      }
    } finally {
      resp.setContentType("text/javascript");
      response.write(writer);
      writer.flush();
      writer.close();
    }
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();
    try {
      String page = req.getParameter("page");
      
      if ("log".equals(page)) {
        resp.setContentType("text/plain; charset=UTF-8");
        
        FileReader reader = new FileReader(System.getProperty("logdir") + req.getParameter("log"));
        char[] cbuf = new char[1024];
        int len = 0;
        StringWriter stringWriter = new StringWriter();
        while ((len = reader.read(cbuf, 0, cbuf.length)) > 0)
          stringWriter.write(cbuf, 0, len);
       
        writer.write(stringWriter.getBuffer().toString());
      } else {
        resp.setContentType("text/html");
        
        File logfileDir = new File(System.getProperty("logdir"));
        File[] logFiles = logfileDir.listFiles();
  
        Arrays.sort(logFiles, new Comparator<File>() {
          @Override
          public int compare(File o1, File o2) {
            if (o1.lastModified() == o2.lastModified())
              return 0;
            if (o1.lastModified() > o2.lastModified())
              return -1;
            else
              return 1;
          }
        });
        
        writer.write("<table border=\"1\"><tr><td>Date</td><td>File</td></tr>");
        
        for (int i = 0; i < logFiles.length; i++) {
          String fileName = logFiles[i].getName();
          writer.write("<tr><td>");
          writer.write(dateFormat.format(new Date(logFiles[i].lastModified())));
          writer.write("</td><td><a href=\"?page=log&log=");
          writer.write(fileName);
          writer.write("\">");
          writer.write(fileName);
          writer.write("</a></td></tr>");
        }
        
        writer.write("</table>");
      }
    } finally {
      writer.flush();
      writer.close();
    }
  }

  private static Logger logger = Logger.getLogger("tcservlet");
  private static DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
}
